<template>
  <div class="common-list-container__v2" v-loading.fullscreen.lock="loading">
    <!--s 头部搜索栏 -->
    <div class="common-list-header__v2">
      <div class="input-with-append-search">
        <el-input class="search-input" placeholder="请输入工单编号/客户信息" v-model="searchParams.keyword" v-trim:blur>
          <el-button type="primary" slot="append" @click="searchParams.pageNum=1;search();trackEventHandler('search')" native-type="submit">搜索</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">重置</el-button>
      </div>
      <span class="advanced-search-btn pointer" @click.self="panelSearchAdvancedToggle">
        <i class="iconfont icon-filter" @click.self="panelSearchAdvancedToggle"></i>
        高级搜索
      </span>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2">
        <!-- todo TASK_BATCH_CLOSE 权限-->
        <el-button type="primary" @click="closeBatch">批量关闭</el-button>
        <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
          选择列
          <i class="iconfont icon-fdn-select"></i>
        </span>
      </div>
      <div
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        已选择
        <span>
          {{ multipleSelection.length }}
        </span>
        条
        <span class="pointer" @click="toggleSelection">清空</span>
      </div>
      <!--s 表格 -->
      <el-table
        ref="table"
        class="common-list-table__v2 mt_8"
        stripe
        :data="taskPage.content"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
      >
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
        ></el-table-column>
        <el-table-column
          v-for="column in columns"
          v-if="column && column.show"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <template v-if="scope.row.state=='closed'">
              <el-button disabled type="text" size="small" :style="{color: '#c0c4cc !important'}">已关闭</el-button>
            </template>
            <template v-else>
              <el-button
                v-if="scope.row.inApprove != 1"    
                type="text"
                size="small"
                :style="{color: '#FF4D4F !important'}"
                @click="closeTask(scope.row)">
                关 闭
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div class="common-list-table-footer__v2 mt_12">
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          :layout="defaultTableData.defaultLayout"
          :total="taskPage.totalElements"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->

    <!-- 高级搜索框 -->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="search"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
    </base-search-drawer>
    <!-- 选择列 --> 
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!-- 工单发起审批弹窗 -->
    <propose-approve-dialog ref="proposeApprove" :remark-required="taskConfig.approveRemark" :task-id="taskApproveId" :task-no="taskNo" />
  </div>
</template>

<script>
// api
import * as TaskApi from '@src/api/TaskApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields} from './fields';
import { defaultTableData } from '@src/util/table'
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import ProposeApproveDialog from '@src/modules/task/view/components/ProposeApproveDialog.vue';

import formatColumn from 'packages/BaseTableCell/formatColumn';
/* mixinx */
import TaskListMixin from '@src/mixins/taskListMixin/index.ts'

const MAXCHECK = 500;

export default {
  name: 'task-close-list',
  mixins: [TaskListMixin],
  data() {
    return {
      defaultTableData,
      taskApproveId: '',
      taskNo:'',
      currentTaskType: {},
      taskTypes: [],
      taskFields: [],
      multipleSelection: [],

      searchParams: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        sorts: []
      },
      taskPage: new Page(),

      visible: false,
      columns: [],
      columnNum: 1,

      loading: false
    }
  },
  computed: {
    // zr_todo:
    taskConfig() {
      return {};
    },
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        ...this.taskFields.filter(filed => { // 过滤重复项
          return !getColumnFields(this).some(item => item.field === filed.fieldName);
        })
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    taskTypeList() {
      return [
        {
          name: '全部', templateId: ''
        },
        ...this.taskTypes
      ]
    },
    serviceTypeDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceType') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    serviceContentDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceContent') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    levelDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'level') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return ['全部', ...dataSource];
    },
    /** 当前选中的工单ids */
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },
    customerSetting(){
      // todo替换
      return {linkmanOn:false, addressOn:true, productOn:true}
    },
    sysFieldsSetting(){
      // todo替换
      return {hasServiceType:true, hasServiceContent:true, hasDescription:true, hasLevel:true}
    },
    paymentConfig(){
      // todo替换
      return {version:1}
    }
  },
  watch: {
    taskFields() {
      this.columns = [
        ...getColumnFields(this),
        ...this.taskFields.filter(f => {
          return f.isSystem !== 1 
          && !['attachment', 'separator', 'info', 'autograph'].includes(f.formType)
        })
      ].map(field => {
        return {
          ...formatColumn(field),
          field: field.field || field.fieldName
        }
      });
    },
    'currentTaskType.id': {
      handler(newVal, oldVal) {
        if(newVal && newVal != oldVal) {
          this.fetchTaskFields();
        }
      }
    }
  },
  methods: {
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：关闭工单-搜索事件');
        return;
      }
    },
    // 工单批量关闭
    async closeBatch() {
      window.TDAPP && TDAPP.onEvent('pc：关闭工单-批量关闭事件');
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$platform.alert('请选择要关闭的工单');
        return;
      }
      try {
        let confirm = await this.$platform.confirm(`当前选中${selectedIds.length}个工单，确定要关闭这些工单吗？`);
        if (confirm) {
          const { status, message} = await TaskApi.closeBatch({ids:selectedIds.join()});
          this.$platform.alert(message);
          if (status == 0) {
            this.multipleSelection = []
            this.fetchTaskList();
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**  获取工单类型 */
    fetchTaskTypesMap() {
      // 如果工单类型列表数据已存在则不查询
      if (this.taskTypes.length > 0) return
    
      return (
        TaskApi.getTaskTypesMap().then((data) => {
          let isSuccess = data.success
          if (!isSuccess) return
        
          this.taskTypes = data?.result || []
          // key : 工单类型id(string) -> value: TaskType
          this.taskTypesMap = (
            this.taskTypes
              .reduce((acc, currentTaskType) => {
                acc[currentTaskType.templateId] = currentTaskType
                return acc
              }, {})
          )
        }).catch(err => {
          console.error(err)
        })
      )
    },
    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：工单关闭列表-高级搜索事件');
      this.visible = true;
    },
    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },
    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          field.show = true;
        });
        this.taskFields = result;
      }).catch(err => {
        console.error(err);
      });
    },
    /** 获取列表数据 */
    fetchTaskList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }

      console.log('搜索参数: ', params);

      this.loading = true;
      TaskApi.search(params)
        .then((res) => {
          this.loading = false;
          this.taskPage = res.result || [];
        })
        .catch(err => {
          this.loading = false;
          console.error(err);
        })
    },
    /** 搜索事件 */
    search () {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      
      if(advancedSearchParams.taskType) {
        let typeId = advancedSearchParams.taskType;
        let taskType = this.taskTypes.find(item => item.templateId === typeId);
        this.currentTaskType = {
          id: typeId,
          name: taskType && taskType.name
        };
      }

      this.fetchTaskList(advancedSearchParams);
      this.closeDrawer();
    },
    /** 打开选择列 */
    showAdvancedSetting(){
      window.TDAPP.onEvent('pc：关闭工单列表-选择列事件');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /** 选择列更新事件 */
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.$message.success(this.$t('common.base.saveSuccess'));
      })
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    /** 表格选择操作: zr_todo */
    handleSelection(selection) {
      let selected = [];

      selected = [
        ...this.multipleSelection,
        ...selection.filter(item => {
          return !this.multipleSelection.some(s => s.id === item.id);
        })
      ];

      if(selected.length > MAXCHECK) {
        return this.$platform.alert(`最多只能选择${MAXCHECK}条数据`);
      }
      
      this.multipleSelection = selection;
    },
    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      if(column === null) {
        this.searchParams.sorts = {};
      }else{
        this.searchParams.sorts = [{
          property: column.isSystem ? prop : `attribute.${prop}`,
          direction: order === 'ascending' ? 'ASC' : 'DESC',
        }]
      }
      
      this.search();
    },
    /** 清空选择框 */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },
    /** 页码跳转 */
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.taskPage.list = [];
      this.search();
    },
    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;

      this.search();
    },
    /** 关闭工单操作 */
    async closeTask(row) {
      window.TDAPP && TDAPP.onEvent('pc：关闭工单-关闭事件');
      let confirm = await this.$platform.confirm('确定要关闭吗？');
      if(!confirm) return
      
      let id = row.id;
      try {
        let res = await TaskApi.checkNotNullForCard({id, flow: 'close'})
        if(res.status == 0) {

          // 先判断是否需要高级审批
          let approveParams = {
            taskId: id,
            action: 'close'
          }

          const approveResult = await TaskApi.checkNeedVipApprove(approveParams);
          if (approveResult.success && approveResult.result.needVipApprove) {
            this.proposeApprove(approveResult.result);
            return
          }

          // 关闭是否需要审批
          const result = await TaskApi.closeApproveCheck({ id });
          if(result.status == 0) {
            this.fetchTaskList();
            return;   
          }
          // TODO 需要审批判断改成errorCode
          if (Number(result.errorCode) == 10003) {
            this.taskApproveId = id;
            this.taskNo = row.taskNo
            this.proposeApprove(result.data);
            return;
          }
          this.$platform.alert(result.message)
        }else{
          this.$platform.alert(res.message)
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** 发起审批 */ 
    proposeApprove(data) {
      this.$refs.proposeApprove.openDialog(data);
    },
  },
  mounted() {
    this.columns = getColumnFields(this);
    // 获取工单类型列表
    this.fetchTaskTypesMap();
    this.fetchTaskList();
    this.fetchTaskFields();
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    [ProposeApproveDialog.name]: ProposeApproveDialog
  }
}
</script>

<style lang="scss" scoped>
.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}
</style>